<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>StructToDocx</title>
  </head>
  <body>
    <div>
      <div style="text-align: center">
        <button id="html-button">Step1: Render HTML</button>
        <button id="docx-button">Step2: Render Docx</button>
      </div>
      <form id="form-container"></form>
    </div>
    <!-- Introducing the DOCX library -->
    <script src="https://cdn.jsdelivr.net/npm/docx@9.5.1/dist/index.iife.min.js"></script>
    <script src="../dist/index.umd.js"></script>
    <script>
      const { DocxBuilder, Packer } = StructToDocx

      // fetch template config
      async function fetchTemplate() {
        const response = await fetch("./assets/template.json")
        if (!response.ok) throw new Error("Failed to fetch template")
        return await response.json()
      }

      // listen render html
      document.querySelector("#html-button").addEventListener("click", async () => {
        const template = await fetchTemplate()
        const htmlBuilder = new DocxBuilder()
        const html = htmlBuilder.setDefaultFont("Arial").setDefaultFontSize(7).addSection(template).renderHtml()
        const formEl = document.querySelector("#form-container")
        formEl.innerHTML = html
      })

      // listen export docx
      document.querySelector("#docx-button").addEventListener("click", async () => {
        const formEl = document.querySelector("#form-container")
        if (!(formEl instanceof HTMLFormElement)) {
          return
        }
        // 手动触发表单校验并提交
        if (!formEl.checkValidity()) {
          // 显示错误提示（浏览器会自动高亮 invalid 字段）
          formEl.reportValidity()
          return
        }
        const formData = new FormData(formEl)
        const data = Object.fromEntries(formData.entries())
        const template = await fetchTemplate()
        // export docx
        const docxBuilder = new DocxBuilder()
        const doc = docxBuilder
          .setProperties({
            title: "QC Report",
            creator: "struct-to-docx",
          })
          .setDefaultFont("Arial")
          .setDefaultFontSize(8)
          .addSection(template)
          .render(data)
        docxBuilder.fileSave(doc, `${Date.now()}`)
      })
    </script>
  </body>
</html>
